import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Match } from '../types/dota'

interface MatchHistoryProps {
  matches: Match[]
  onMatchClick?: (matchId: number) => void
}

export default function MatchHistory({ matches, onMatchClick }: MatchHistoryProps) {
  const [heroes, setHeroes] = useState<any>({})
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchHeroes = async () => {
      try {
        const response = await fetch('https://api.opendota.com/api/heroes')
        const heroData = await response.json()
        const heroMap = heroData.reduce((acc: any, hero: any) => {
          acc[hero.id] = hero
          return acc
        }, {})
        setHeroes(heroMap)
      } catch (error) {
        console.error('Failed to fetch heroes:', error)
      } finally {
        setLoading(false)
      }
    }

    fetchHeroes()
  }, [])

  // 添加英雄名称转换函数
  const getHeroImageUrl = (heroName: string) => {
    // 移除 "npc_dota_hero_" 前缀
    const cleanName = heroName.replace('npc_dota_hero_', '')
    return `http://cdn.dota2.com/apps/dota2/images/heroes/${cleanName}_lg.png`
  }

  const formatDuration = (duration: number) => {
    const minutes = Math.floor(duration / 60)
    const seconds = duration % 60
    return `${minutes}:${seconds.toString().padStart(2, '0')}`
  }

  const formatDate = (startTime: number) => {
    const date = new Date(startTime * 1000)
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
  }

  const getGameMode = (gameMode: number) => {
    const modes: { [key: number]: string } = {
      1: 'All Pick',
      2: 'Captain\'s Mode',
      3: 'Random Draft',
      4: 'Single Draft',
      5: 'All Random',
      16: 'Captain\'s Draft',
      22: 'Ranked All Pick',
      23: 'Turbo'
    }
    return modes[gameMode] || `Mode ${gameMode}`
  }

  if (loading) {
    return (
      <Card className="modern-card">
        <CardHeader>
          <CardTitle className="text-xl font-bold text-foreground flex items-center space-x-2">
            <span>📊</span>
            <span>Match History</span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center py-12">
            <div className="flex items-center space-x-3">
              <div className="loading-spinner w-6 h-6"></div>
              <span className="text-muted-foreground">Loading match history...</span>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  if (!matches || matches.length === 0) {
    return (
      <Card className="modern-card">
        <CardHeader>
          <CardTitle className="text-xl font-bold text-foreground flex items-center space-x-2">
            <span>📊</span>
            <span>Match History</span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-12">
            <div className="text-4xl mb-4">🎮</div>
            <div className="text-lg font-medium text-foreground mb-2">No Match Records</div>
            <div className="text-muted-foreground">No recent matches found for this player</div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card className="modern-card">
      <CardHeader>
        <CardTitle className="text-xl font-bold text-foreground flex items-center space-x-2">
          <span>📊</span>
          <span>Match History</span>
        </CardTitle>
        <CardDescription className="text-muted-foreground">
          Recent {matches.length} matches
        </CardDescription>
      </CardHeader>
      <CardContent>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[80px]">Result</TableHead>
              <TableHead className="text-left">Hero</TableHead>
              <TableHead className="text-center">KDA</TableHead>
              <TableHead className="text-center">GPM/XPM</TableHead>
              <TableHead className="text-center">LH/DN</TableHead>
              <TableHead className="text-center">Duration</TableHead>
              <TableHead className="text-center">Mode</TableHead>
              <TableHead className="text-right">Date</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {matches.map((match) => {
              const hero = heroes[match.hero_id]
              const isWin = (match.player_slot < 128 && match.radiant_win) || 
                           (match.player_slot >= 128 && !match.radiant_win)
              
              return (
                <TableRow 
                  key={match.match_id} 
                  className="hover:bg-muted/50 cursor-pointer transition-colors"
                  onClick={() => onMatchClick?.(match.match_id)}
                >
                  <TableCell>
                    <Badge 
                      variant={isWin ? "default" : "destructive"}
                      className={`${
                        isWin 
                          ? 'bg-green-600 hover:bg-green-700' 
                          : 'bg-red-600 hover:bg-red-700'
                      } text-white font-medium`}
                    >
                      {isWin ? 'W' : 'L'}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-left">
                    <div className="flex items-center space-x-3">
                      {hero && (
                        <img
                          src={getHeroImageUrl(hero.name)}
                          alt={hero.localized_name}
                          className="w-12 h-8 rounded border border-border object-cover"
                          onError={(e) => {
                            // 如果图片加载失败，尝试使用备用URL
                            const target = e.target as HTMLImageElement
                            if (!target.src.includes('_sb.png')) {
                              const cleanName = hero.name.replace('npc_dota_hero_', '')
                              target.src = `http://cdn.dota2.com/apps/dota2/images/heroes/${cleanName}_sb.png`
                            }
                          }}
                        />
                      )}
                      <div className="min-w-0">
                        <div className="font-medium text-foreground truncate">
                          {hero?.localized_name || 'Unknown Hero'}
                        </div>
                      </div>
                    </div>
                  </TableCell>
                  
                  <TableCell className="text-center">
                    <div className="font-mono text-sm">
                      <span className="text-green-600 font-semibold">{match.kills}</span>
                      <span className="text-muted-foreground mx-1">/</span>
                      <span className="text-red-600 font-semibold">{match.deaths}</span>
                      <span className="text-muted-foreground mx-1">/</span>
                      <span className="text-blue-600 font-semibold">{match.assists}</span>
                    </div>
                  </TableCell>
                  
                  <TableCell className="text-center">
                    <div className="text-sm">
                      <div className="font-medium">{match.gold_per_min}</div>
                      <div className="text-muted-foreground text-xs">{match.xp_per_min}</div>
                    </div>
                  </TableCell>
                  
                  <TableCell className="text-center">
                    <div className="text-sm">
                      <div className="font-medium">{match.last_hits}</div>
                      <div className="text-muted-foreground text-xs">{match.denies}</div>
                    </div>
                  </TableCell>
                  
                  <TableCell className="text-center">
                    <div className="text-sm font-medium">
                      {formatDuration(match.duration)}
                    </div>
                  </TableCell>
                  
                  <TableCell className="text-center">
                    <div className="text-xs text-muted-foreground">
                      {getGameMode(match.game_mode)}
                    </div>
                  </TableCell>
                  
                  <TableCell className="text-right">
                    <div className="text-xs text-muted-foreground">
                      {formatDate(match.start_time)}
                    </div>
                  </TableCell>
                </TableRow>
              )
            })}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  )
}